import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/settings_dao.dart';
import 'package:changxindianzishangwu/dao/upload_file_dao.dart';
import 'package:changxindianzishangwu/dao/user_info_dao.dart';
import 'package:changxindianzishangwu/model/dynamic_media_model.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/model/user_settings_model.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/event_bus.dart';
import 'package:changxindianzishangwu/util/show_custom_bottom_sheet.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart' as Intent;
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

import 'common_language_page.dart';

class ChatManagementPage extends StatefulWidget {
  ChatManagementPage({Key key}) : super(key: key);

  @override
  _ChatManagementPageState createState() => _ChatManagementPageState();
}

class _ChatManagementPageState extends State<ChatManagementPage> {
  var _lightsDzh = false;
  var _lightsHf = false;
  var _isChange=false;

  @override
  void initState() {
    // TODO: implement initState
    getSettingsData();
    super.initState();
  }
  @override
  void dispose() {
    print('------EventBus----AAAA----$_isChange');
    EventBus().commit(EventKeys.EVENT_BUS_SETTINGS, _isChange);
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    print('userID${getUserInfo().userId}');
    return Scaffold(
      appBar: TopAppBar(
        context,
        "聊天管理",
      ),
      body: Column(
        children: [
          Container(
            alignment: Alignment.center,
            color: Colors.white,
            margin: EdgeInsets.only(top: 10),
            child: Column(
              children: <Widget>[
                MergeSemantics(
                  child: ListTile(
                    title: Text(
                      '添加好友打招呼',
                      style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                    ),
                    trailing: CupertinoSwitch(
                      activeColor: Color.fromRGBO(0, 220, 169, 1),
                      value: _lightsDzh,
                      onChanged: (bool value) {
                        setState(() {
                          _lightsDzh = value;
                          _updateSettings();
                        });
                      },
                    ),
                    onTap: () {
                      setState(() {
                        _lightsDzh = !_lightsDzh;
                        _updateSettings();
                      });
                    },
                  ),
                ),
                Divider(
                  height: 1,
                  indent: ScreenUtil().setWidth(10),
                  color: Color.fromRGBO(248, 248, 248, 1),
                  thickness: ScreenUtil().setHeight(1),
                ),
                InkWell(
                  onTap: () {
                    Intent.Get.to(() => CommonLanguagePage(1));
                  },
                  child: ListTile(
                    leading: Text(
                      "打招呼内容",
                      style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                    ),
                    trailing: Icon(Icons.keyboard_arrow_right),
                  ),
                ),
              ],
            ),
          ),
          Container(
            alignment: Alignment.center,
            color: Colors.white,
            margin: EdgeInsets.only(top: 10),
            child: Column(
              children: <Widget>[
                MergeSemantics(
                  child: ListTile(
                    title: Text(
                      '忙碌自动回复',
                      style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                    ),
                    trailing: CupertinoSwitch(
                      activeColor: Color.fromRGBO(0, 220, 169, 1),
                      value: _lightsHf,
                      onChanged: (bool value) {
                        setState(() {
                          _lightsHf = value;
                          _updateSettings();
                        });
                      },
                    ),
                    onTap: () {
                      setState(() {
                        _lightsHf = !_lightsHf;
                        _updateSettings();
                      });
                    },
                  ),
                ),
                Divider(
                  height: 1,
                  indent: ScreenUtil().setWidth(10),
                  color: Color.fromRGBO(248, 248, 248, 1),
                  thickness: ScreenUtil().setHeight(1),
                ),
                InkWell(
                  onTap: () {
                    Intent.Get.to(() => CommonLanguagePage(2));
                  },
                  child: ListTile(
                    leading: Text(
                      "自动回复内容",
                      style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                    ),
                    trailing: Icon(Icons.keyboard_arrow_right),
                  ),
                ),
              ],
            ),
          ),
          InkWell(
            onTap: () {
              Intent.Get.to(() => CommonLanguagePage(3));
            },
            child: Container(
              color: Colors.white,
              margin: EdgeInsets.only(top: 10),
              alignment: Alignment.center,
              child: ListTile(
                leading: Text(
                  "常用语",
                  style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                ),
                title: Container(
                  alignment: Alignment.centerRight,
                  height: ScreenUtil().setHeight(50),
                  width: ScreenUtil().setWidth(50),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(4),
                  ),
                ),
                trailing: Icon(Icons.keyboard_arrow_right),
              ),
            ),
          ),
          InkWell(
            onTap: () {
              _selectAction();
            },
            child: Container(
              color: Colors.white,
              margin: EdgeInsets.only(top: 10),
              alignment: Alignment.center,
              child: ListTile(
                leading: Text(
                  "聊天背景",
                  style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                ),
                title: Container(
                  alignment: Alignment.centerRight,
                  height: ScreenUtil().setHeight(50),
                  width: ScreenUtil().setWidth(50),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(4),
                  ),
                ),
                trailing: Icon(Icons.keyboard_arrow_right),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void getSettingsData() async {
    UserSettingsModel model = await SettingsDao.getUserSettings();
    if (model.resultCode == 0) {
      toast("提示：${model.resultMsg}");
      return;
    }

    if (mounted)
      setState(() {
        switch (model.data.sayHello) {
          case 0:
            _lightsDzh = false;
            _lightsHf = false;
            break;
          case 1:
            _lightsDzh = true;
            _lightsHf = false;
            break;
          case 2:
            _lightsDzh = false;
            _lightsHf = true;
            break;
          case 3:
            _lightsDzh = true;
            _lightsHf = true;
            break;
        }
      });
  }

  void _updateSettings() async {
    int sayHello;
    if (_lightsDzh && _lightsHf) {
      sayHello = 3; //都开启
    }
    if (!_lightsDzh && _lightsHf) {
      sayHello = 2; //开启回复
    }
    if (_lightsDzh && !_lightsHf) {
      sayHello = 1; //开启打招呼                       1      2
    }
    if (!_lightsDzh && !_lightsHf) {
      sayHello = 0; //关闭
    }
    print('---sayHello----$sayHello');

    var result = await SettingsDao.updateSettingsSayHello("sayHello",sayHello);
    if (result["resultCode"] == 0) {
      toast("修改失败：${result["resultCode"]}");
      return;
    }
    _isChange=true;
    UserInfo userInfo = getUserInfo();
    userInfo.settings.sayHello = sayHello;
    setUserinfoModel(userInfo);
    toast("修改成功");
  }

  void _selectAction() async {
    int index = await showDialog(context: context, title: '修改聊天背景');
    if (index == 1) {
      _photoSelect();
      // Navigator.pop(context, '拍照');
    }
    if (index == 2) {
      _imagesSelect();
      // Navigator.pop(context, '从相册选择');
    }
  }

  Future<int> showDialog({
    @required BuildContext context,
    @required String title,
  }) {
    return showCustomBottomSheet(
        context: context,
        title: title,
        cancelTextColor: AppColor.colorDialog,
        children: [
          actionItem(
              context: context,
              index: 1,
              title: '拍摄',
              color: AppColor.colorDialog),
          actionItem(
              context: context,
              index: 2,
              title: '从相册选择',
              isLastOne: true,
              color: AppColor.colorDialog),
        ]);
  }

  _imagesSelect() async {
    await _handleCameraAndMic();
    await ImagePicker()
        .getImage(source: ImageSource.gallery)
        .then((value) => _updatePhoto(value.path));
  }

  _photoSelect() async {
    await ImagePicker()
        .getImage(source: ImageSource.camera)
        .then((value) => _updatePhoto(value.path));
    // if (pickedFile == null) return;
  }

  _handleCameraAndMic() async {
    // 申请权限

    bool a = await await Permission.photos.request().isGranted;
    print(a);
    if (a == true) {
      print(a);
      print("已经打开");
    } else {
      showToast("请打开图库权限");
      await Future.delayed(Duration(seconds: 1));
      print(a);
      openAppSettings();
    }
  }

  _updatePhoto(String path) async {
    EasyLoading.show(status: "正在上传背景图...");
    FormData formData = FormData();
    formData.files.add(MapEntry(
        "files",
        MultipartFile.fromFileSync(path,
            filename:
                "photo_${new DateTime.now().millisecondsSinceEpoch}.png")));
    DynamicMediaModel value = await UpLoadFileDao.addFile(formData);
    if (value.resultCode == 1) {
      String path = value.data.images[0].oUrl;

      UserInfoModel userInfoModel =
          await UserInfoDao.updateUserInfo("chatBackGroundUrl", path);

      EasyLoading.dismiss();
      if (userInfoModel.resultCode == 0) {
        toast("上传失败${userInfoModel.resultMsg}");
        return;
      }
      toast("修改成功");
    } else {
      EasyLoading.dismiss();
      toast("上传失败");
    }
  }
}
